<template>
	<view class="enterPay">
		<view class="card">
			<view class="oneLine flex-center">
				<view class="text">订单金额</view>
				<view class="moneyBox">{{money}}<text>元</text></view>
			</view>
		</view>
		
		<view style="padding: 30rpx;">
			<m-pay-radio
				@payType="getPayType"
				:payList="payList">
			</m-pay-radio>
		</view>
		
		<view
			class="submitBtn flex"
			@click="showPayKeyboard">确认支付</view>
		
		<uni-popup
			ref="popupCircleDraw"
			:is-mask-click="false"
			type="center">
			<view class="circleDrawTipBox">
				<image
					src="https://wx.2024csnl.com/static/business/circleDraw.png"
					mode="widthFix"
					@click="gotoCircleDraw"></image>
			</view>
		</uni-popup>
		
		<uni-popup ref="popupPayTips" type="center">
			<view class="hintModalPayTipBox">
				<view class="title">支付中</view>
				<view>
					正在查询支付结果，请等待...
				</view>
				<view class="btnBox">
					<view
						class="btn flex-center"
						@click="onCancelPayment">我已取消支付</view>
				</view>
			</view>
		</uni-popup>

		<pay-keyboard
			:show_key="show_pay_keyboard"
			@hideFun="hidePayKeyboard"
			:show_forget="true"
			@getPassword="getPayPassword">
		</pay-keyboard>
	</view>
</template>

<script>
	import {
		setImmediatePayment,
		getOrderPayStatus,
		haveRaffleTicket,
		getAppConfig,
		checkpaypwdRequest,
		getPersonalCenter
	} from "@/api/index.js"
	import {
		hex_md5
	} from "@/utils/md5.js";
	export default {
		data() {
			return {
				bid: 0,
				webview: '',
				show_pay_keyboard: false,
				payPassword: '',
				isPayCircleDraw: false,
				baseUrl: '',
				payType: 2,
				payList: [2],
				pageType: '',
				money: '',
				orderid: '',
				orderStatusTimer: 0,
				isJumpToPayApp: false,
				chouJiangId: 0
			}
		},
		async onLoad(opt) {
			// #ifdef APP-PLUS
			var $this = this;
			plus.globalEvent.addEventListener('plusMessage', msg => {
				if (msg.data.args.data.name == 'postMessage') {
					const info = msg.data.args.data.arg
					console.log(info)
					if (info.action == "close") {
						try {
							$this.webview.close()
						} catch (e) {}

					}

					if (info.action == "cancel") {
						try {
							$this.webview.close()
						} catch (e) {}

						this.showToast('付款失败')

						this.close('popupPayTips')

						uni.navigateBack({
							delta: 1
						});

					}
				}
			})
			// #endif

			const appConfig = await getAppConfig()
			console.log(appConfig)
			this.isPayCircleDraw = appConfig.isPayCircleDraw
			this.money = opt.money
			this.orderid = opt.orderId
			this.pageType = opt.pageType
			this.baseUrl = getApp().globalData.BASE_URL;
			this.bid = opt.bid;

			if (this.bid == '5') {
				this.payList = [2]
				this.payType = 2
			} else {
				this.payList = appConfig.payList
				this.payType = this.payList[0]
			}
		},
		onShow() {
			if ((this.payType == 201 || this.payType == 202 || this.payType == 203) && this.isJumpToPayApp) {
				this.orderStatusTimer = setInterval(() => {
					this.getOrderStatus();
				}, 1000)
			}
		},
		onHide() {
			if ((this.payType == 201 || this.payType == 202 || this.payType == 203) && this.orderStatusTimer > 0) {
				clearInterval(this.orderStatusTimer)
			}
		},
		methods: {

			gotoCircleDraw() {
				this.close('popupCircleDraw')
				uni.reLaunch({
					url: `/package/mine/circleDraw?id=${this.chouJiangId}&pageType=1`
				});
			},
			async showPayKeyboard() {
				if (this.payType == 1 || this.payType == 100 || this.payType == 200) {
					this.show_pay_keyboard = true
				} else {
					await this.onSetImmediatePayment()
				}
			},
			hidePayKeyboard() {
				this.show_pay_keyboard = false
			},
			async getPayPassword(n) {
				console.log("用户输入的密码", n)
				this.payPassword = n.password;
				this.show_pay_keyboard = false

				const res = await checkpaypwdRequest('s=/ApiMy/checkpaypwd', {
					paypwd: this.payPassword
				})
				const {
					status,
					msg
				} = res.data
				console.log(res)
				if (status == 1) {
					await this.onSetImmediatePayment()
				} else {
					this.showToast(msg)
				}
			},
			// 支付后是否能抽奖
			async getHaveRaffleTicket() {
				setTimeout(async () => {
					const res = await haveRaffleTicket('s=/ApiChoujiang/payafter', {
						orderid: this.orderid,
						ordertype: this.pageType == 'join' ? 'member_levelup_order' : 'shop_order'
					})
					const {
						status,
						id,
						msg
					} = res.data

					if (status == 1) {
						this.showToast('付款成功')
						this.onGoPage(1, id)
					} else if (status == 0) {
						this.showToast('付款成功')
						this.onGoPage(0)
					} else {
						this.showToast(msg)
					}
				}, 500);
			},
			// 判断跳转页面,有抽奖跳抽奖,没抽奖跳tabbar页面
			onGoPage(type, id) {
				setTimeout(() => {
					if (type == 1 && this.isPayCircleDraw) {
						this.chouJiangId = id;
						this.pageType == 'join' ? this.gotoJinJian() : this.open('popupCircleDraw');
					} else {
						this.pageType == 'join' ? this.gotoJinJian() : this.switchTabbar(
							getApp().globalData.HOME_PAGE)
					}
				}, 2000)
			},
			async gotoJinJian() {
				this.onSkip(`/package/mine/jinjian`)
			},
			// 立即支付
			async onSetImmediatePayment() {
				console.log(getApp().globalData.BASE_URL)
				console.log(this.payType)
				const res = await setImmediatePayment('s=/ApiPay/pay', {
					op: 'submit',
					orderid: this.orderid,
					typeid: this.payType
				})
				const {
					data,
					status,
					msg
				} = res.data
				console.log("发送参数")
				console.log({
					op: 'submit',
					orderid: this.orderid,
					typeid: this.payType,
				})
				console.log("返回")
				console.log(res)
				if (status == 2 || status == 1) {
					//余额支付
					if (this.payType == 1) {
						this.showToast(res.data.msg)
						this.getHaveRaffleTicket()
					}
					// 积分(泌豆)支付
					if (this.payType == 100) {
						this.showToast(res.data.msg)
						this.getHaveRaffleTicket()
					}
					// 积分(泌豆)支付
					if (this.payType == 200) {
						this.showToast(res.data.msg)
						this.getHaveRaffleTicket()
					}
					// 云闪付支付
					if (this.payType == 204) {
						this.onUPPay(data.prepay_id, 'wxpay')
					}
					// 微信支付
					if (this.payType == 2) {
						this.onAliOrWchatPay(data.data, 'wxpay')
					}
					// 支付宝支付
					if (this.payType == 3) {
						// #ifdef H5
						document.querySelector('body').innerHTML = data;
						document.forms[0].submit()
						// #endif
						// #ifdef APP-PLUS
						this.onAliOrWchatPay(data, 'alipay')
						// #endif
					}

					if (this.payType == 201) {
						//this.onAliOrWchatPay(data.data, 'wxpay')
						// #ifdef H5
						window.location.href  = data.prepay_id;
						// #endif
						// #ifdef APP-PLUS
						this.onAliOrWchatPay(data, 'wxpay')
						// #endif
						// this.isJumpToPayApp = true;
						// var that = this
						// uni.getSystemInfo({
						// 	success(res) {
						// 		if (res.platform == 'android') {
						// 			var clickButton = function() {
						// 				that.webview.close();
						// 			}
						// 			that.webview = plus.webview.create(data.prepay_id, "payweb", {
						// 				titleNView: {
						// 					autoBackButton: false,
						// 					titleText: '',
						// 					buttons: [{
						// 						type: 'close',
						// 						float: 'left',
						// 						onclick: clickButton
						// 					}]
						// 				}
						// 			})
						// 			that.webview.show();

						// 			that.open('popupPayTips')
						// 			that.orderStatusTimer = setInterval(async () => {
						// 				await that.getOrderStatus()
						// 			}, 1000)
						// 		} else {
						// 			plus.runtime.openURL(data.prepay_id, function(openUrlRes) {
						// 				console.log(openUrlRes);
						// 			});
						// 			that.open('popupPayTips')
						// 			that.orderStatusTimer = setInterval(async () => {
						// 				await that.getOrderStatus()
						// 			}, 1000)
						// 		}
						// 	},
						// });
					}

					if (this.payType == 203) {
						this.isJumpToPayApp = true;
						var that = this
						uni.getSystemInfo({
							success(res) {
								if (res.platform == 'android') {
									var clickButton = function() {
										that.webview.close();
									}
									that.webview = plus.webview.create(data.prepay_id, "payweb", {
										titleNView: {
											autoBackButton: false,
											titleText: '',
											buttons: [{
												type: 'close',
												float: 'left',
												onclick: clickButton
											}]
										}
									})
									that.webview.show();

									that.open('popupPayTips')
									that.orderStatusTimer = setInterval(async () => {
										await that.getOrderStatus()
									}, 1000)
								} else {
									plus.runtime.openURL(data.prepay_id, function(openUrlRes) {
										console.log(openUrlRes);
									});
									that.open('popupPayTips')
									that.orderStatusTimer = setInterval(async () => {
										await that.getOrderStatus()
									}, 1000)
								}
							},
						});
					}

					if (this.payType == 202) {
						console.log(res)
						this.isJumpToPayApp = true;
						var that = this

						uni.getSystemInfo({
							success(res) {
								if (res.platform == 'android') {
									plus.runtime.openURL(data.prepay_id, function(openUrlRes) {
										console.log(openUrlRes);
									});
									that.open('popupPayTips')
									that.orderStatusTimer = setInterval(async () => {
										await that.getOrderStatus()
									}, 1000)
								} else {
									plus.runtime.openURL(data.prepay_id.replace("alipays://", "alipay://"),
										function(openUrlRes) {
											console.log(openUrlRes);
										});
									that.open('popupPayTips')
									that.orderStatusTimer = setInterval(async () => {
										await that.getOrderStatus()
									}, 1000)
								}
							},
						});
					}
				} else {
					let msgText = msg ? msg : '支付错误,暂未开通该支付'
					this.showToast(msgText)
				}
			},
			async onAliOrWchatPay(data, payType) {
				//console.log(data)

				var payData = {
					provider: payType,
					orderInfo: data,
					timeStamp: data.timeStamp,
					nonceStr: data.nonceStr,
					package: data.package,
					signType: data.signType,
					paySign: data.paySign,
					success: (res) => {
						this.getHaveRaffleTicket()
					},
					fail: (err) => {
						console.log(err)
						uni.showToast({
							title: '支付失败',
							icon: 'none'
						})
					}
				};
				uni.requestPayment(payData);
				// uni.requestPayment({
				// 	provider: payType,
				// 	orderInfo: data,
				// 	success: (res) => {
				// 		this.getHaveRaffleTicket()
				// 	},
				// 	fail: (err) => {
				// 		console.log(err)
				// 		uni.showToast({
				// 			title: '支付失败',
				// 			icon: 'none'
				// 		})
				// 	}
				// });
			},
			async onUPPay(data, payType) {
				const sappPlugin = uni.requireNativePlugin('sapppay');
				sappPlugin.pay({
					tn: data,
					serverMode: "00"
				}, (res) => {
					if (res.result == 'success') {
						this.getHaveRaffleTicket()
					} else {
						uni.showToast({
							title: '支付失败',
							icon: 'none'
						})
					}
				})
			},
			getPayType(e) {
				console.log("dfsdfds")
				console.log(e)
				this.payType = e
			},
			open(n) {
				this.$refs[n].open();
			},
			close(n) {
				this.$refs[n].close();
			},
			onCancelPayment() {
				clearInterval(this.orderStatusTimer)
				this.close('popupPayTips')

				uni.navigateBack({
					delta: 1
				});
			},
			async getOrderStatus() {
				const res = await getOrderPayStatus('s=/ApiPay/paystatus', {
					orderid: this.orderid
				})
				const {
					id,
					status,
					msg
				} = res.data
				console.log(res)
				if (status == 1) {
					clearInterval(this.orderStatusTimer)
					this.close('popupPayTips')

					try {
						this.webview.close()
					} catch (e) {}

					if (id > 0) {
						this.showToast('付款成功')
						this.onGoPage(1, id)
					} else {
						this.showToast('付款成功')
						this.onGoPage(0)
					}
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.text {
		color: #999999;
		font-size: 32rpx;
		margin-bottom: 32rpx;
	}

	.moneyBox {
		color: #333;
		font-size: 38rpx;
		font-weight: bold;

		text {
			font-size: 28rpx;
			font-weight: 500;
			margin-left: 15rpx;
		}
	}

	.card {
		font-size: 36rpx;
		background: #fff;
		font-weight: 500;
		margin-bottom: 75rpx;

		.oneLine {
			padding: 25rpx 30rpx;
			flex-direction: column;
		}

	}

	.enterPay {
		background: #F7F7F7;
		min-height: 94.5vh;
	}

	.submitBtn {
		margin: 10vh 30rpx 0;
		color: #fff;
		font-size: 34rpx;
		background: #41644A;
		border-radius: 80rpx;
		padding: 30rpx 0;
		justify-content: center;
	}


	.hintModalPayTipBox {
		padding: 30rpx;
		border-radius: 30rpx;
		width: 600rpx;
		background: #fff;
		height: 300rpx;
		overflow: auto;
		line-height: 50rpx;
		color: #333333;
		font-size: 32rpx;

		.title {
			text-align: center;
			color: #F40E2A;
			font-weight: bold;
			margin-bottom: 30rpx;
		}

		.btnBox {
			display: flex;
			flex-direction: row;

			.btn {
				flex: 1;
				padding: 20rpx;
				height: 60rpx;
				background: #F40E2A;
				color: #FFFFFF;
				border-radius: 20rpx;
				margin-top: 50rpx;
			}
		}

	}
</style>